package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

public class ObjectMapperUtil {
    //定义常亮对象  优势1.对象独一份,节省空间  优势2.对象不允许别人随意更改
    private static final ObjectMapper objectMapper = new ObjectMapper();
    //1.将任意对象转换为json
    public static String toJson(Object object){
        try {
            if(object==null){
                throw new RuntimeException("传递的参数为空");
            }
           String json = objectMapper.writeValueAsString(object);
            return json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //将检查的异常转化为运行时异常
            throw new RuntimeException("转化有误");
        }
    }

    //2.将任意json装换为对象
    public static <T> T  toObject(String json,Class<T> cls){
        try {
            if(StringUtils.isEmpty(json) || cls==null){
                throw new RuntimeException("参数异常");
            }
           return objectMapper.readValue(json,cls);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("转化失败");
        }
    }
}
